package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties minioProperties;

    /**
     * 文件上传到MinIO
     *
     * @param file 文件
     * @return MinIO中的文件的url
     */
    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        // 判断bucket是否存在
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        // 如果不存在则创建bucket
        if (!found) {
            // 创建bucket
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            // 获取访问权限文本
            String policyJson = createBucketPolicyConfig(minioProperties.getBucketName());
            // 设置bucket的访问权限
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config(policyJson).build());

        }

        // 如果存在则直接开始上传文件
        // 上传inputStream流（SpringBoot接收浏览器发送的文件解析为InputStream流（二进制数据流））文件
        String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String fileName = currentDate + "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
        minioClient.putObject(
                PutObjectArgs
                        .builder()
                        .bucket(minioProperties.getBucketName())
                        .object(fileName)
                        // parSize：分片参数
                        // -1：根据fileSize的大小自动进行分片上传
                        // >0：设置分片大小
                        .stream(file.getInputStream(), file.getSize(), -1)
                        // 不设置ContentType：下载文件
                        // 设置ContentType：预览文件
                        .contentType(file.getContentType())
                        .build()
        );
        return String.join("/", minioProperties.getEndpoint(), minioProperties.getBucketName(), fileName);
    }

    /**
     * 自定义MinIO的bucket访问权限
     */
    private String createBucketPolicyConfig(String bucketName) {

        return """
                {
                  "Statement" : [ {
                    "Action" : "s3:GetObject",
                    "Effect" : "Allow",
                    "Principal" : "*",
                    "Resource" : "arn:aws:s3:::%s/*"
                  } ],
                  "Version" : "2012-10-17"
                }
                """.formatted(bucketName);
    }
}
